package oglutil

import (
	"fmt"
	"image"
	"image/draw"
	"image/jpeg"
	"image/png"
	"os"
	"strings"

	"github.com/go-gl/gl/v4.6-core/gl"
)

//Texture 纹理
type Texture struct {
	ID   uint32
	file string
}

//NewTexture 返回1张纹理
func NewTexture(file string) *Texture {
	return &Texture{file: file}
}

//Gen 生成纹理
func (tx *Texture) Gen(wraps, wrapt, minf, magf int32) error {
	rgba, err := imageToPixelData(tx.file)
	if err != nil {
		return err
	}
	gl.GenTextures(1, &tx.ID)
	//gl.ActiveTexture(gl.TEXTURE0)
	var lastTxID int32
	gl.GetIntegerv(gl.TEXTURE_BINDING_2D, &lastTxID)
	gl.BindTexture(gl.TEXTURE_2D, tx.ID)

	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wraps)
	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrapt)

	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minf)
	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magf)

	gl.TexImage2D(
		gl.TEXTURE_2D,
		0,
		gl.RGBA,
		int32(rgba.Rect.Size().X),
		int32(rgba.Rect.Size().Y),
		0,
		gl.RGBA,
		gl.UNSIGNED_BYTE,
		gl.Ptr(rgba.Pix))
	gl.GenerateMipmap(gl.TEXTURE_2D)
	//恢复原来的
	gl.BindTexture(gl.TEXTURE_2D, uint32(lastTxID))
	//gl.BindTexture(gl.TEXTURE_2D, 0)
	return nil
}

func imageToPixelData(file string) (*image.RGBA, error) {
	imgFile, err := os.Open(file)
	if err != nil {
		return nil, fmt.Errorf("texture %q not found on disk: %v", file, err)
	}
	defer imgFile.Close()
	var img image.Image
	if strings.HasSuffix(file, ".png") {
		img, err = png.Decode(imgFile)
	} else {
		img, err = jpeg.Decode(imgFile)
	}
	if err != nil {
		return nil, err
	}

	rgba := image.NewRGBA(img.Bounds())
	if rgba.Stride != rgba.Rect.Size().X*4 {
		return nil, fmt.Errorf("unsupported stride")
	}
	draw.Draw(rgba, rgba.Bounds(), img, image.Point{0, 0}, draw.Src)
	return rgba, nil
}
